import axiosInstance from "./axiosInstance"
import { ElMessage } from "element-plus";
import type { Music, FactoryResult, FriendRequest, PullGroupBasicInfo, RecommendAndUser, StockGroupMessage, StockPrivateMessage } from "../types/types";
import { connectWebSocket } from "./webSocketService";
import { pullGroupChats } from "../components/General/Contact/contact";
import { factoryStatus, setFactoryMounted } from "../eventBus";
import { userStore } from "../store/userStore";
import { friendStore } from "../store/friendStore";
import { useFactory } from "./factory";
import { reactive } from "vue";
import { musicStore } from "../store/musicStore";

let result: FactoryResult = reactive({
    user_store: null,
    friend_store: null,
    chat_store: null
})

export async function callFactory(): Promise<FactoryResult> {
    try {
        const factory = await useFactory();
        // 告知事件总线加载完毕
        setFactoryMounted();
        return factory;
    } catch (error) {
        console.error(error)
        return result;
    }
}


// 通用的错误处理逻辑
const handleError = (error: any): void => {
    if (error.response) {
        switch (error.response.status) {
            case 401:
                ElMessage.warning("用户认证过期，重新认证");
                userStore().clearUserInfo();
                break;
            case 500:
                ElMessage.error(error.response.data.message);
                break;
            default:
                ElMessage.error("发生错误：" + error.response.data.message || error.response.data);
                break;
        }
    } else {
        ElMessage.error("发生错误：" + error.message);
    }
}

// 通用的http请求逻辑
const makeRequest = async (url: string, method: "get" | "post" | "delete", data?: any, headers?: any) => {
    try {
        const response = await axiosInstance.request({
            url: url,
            method: method,
            data: data,
            headers: headers
        });
        return response;
    } catch (error: any) {
        handleError(error);
        throw error;
    }
}

// 验证用户token是否有效
export const validToken = async (): Promise<void> => {
    const user_store = userStore();
    try {
        let url = "http://localhost:8080/camelia/validToken";
        const response = await axiosInstance.post(url, {}, {
            headers: {
                'Authorization': `Bearer ${user_store.userInfo.token}`,
                'Content-Type': 'application/json'
            }
        })
        if (response && response.data.status === "OK") {
            connectWebSocket();
        }
    } catch (error: any) {
        if (error.response.status === 401) {
            ElMessage.warning("用户认证过期，重新认证");
            user_store.setStatus();
            user_store.clearUserInfo();
        }
    }
}

// 获取对应消息对话消息队列         senderId是发送者uuId，chatId是接收者uuId
// export const getChatStoreMessage = async (senderId: string, chatId: string): Promise<any> => {
//     let url = `http://localhost:8080/camelia/get-chat-message/${senderId}/${chatId}`
//     try {
//         const response = await axiosInstance.post(url);
//         return response;
//     } catch (error: any) {
//         if (error && error.response.status === 500) {
//             ElMessage.error(error.response.data.message)
//         }
//     }
// }

// 获取随机好友
export const getRecommendFriends = async () => {
    const friend_store = friendStore();
    const url = `http://localhost:8080/camelia/random-recomment-friends`;
    try {
        const response = await axiosInstance.get(url);
        if (response.data) {
            response.data.forEach((friend: RecommendAndUser) => {
                friend_store.storageRecommendFriends(friend);
            });
        }
    } catch (error: any) {
        ElMessage.error("获取好友推荐失败");
        console.error(error);
    }
};


// 获取好友请求信息
export const getFriendRequestInfo = async (): Promise<any> => {
    const url = `http://localhost:8080/camelia/get-friend-request-message-info/${userStore().userInfo.uu_id}`;
    try {
        const response = await axiosInstance.post(url);
        if (response) {
            return response.data;
        }
    } catch (error: any) {
        if (error && error.response.status === 401) {
            // ElMessage.error(error.response.data.data);
        }
    }
}


// 同意好友请求的api
export const acceptFriendRequest = async (friend: FriendRequest): Promise<void> => {
    // const url = `http://localhost:8080/camelia/accept-friend-request/${friendId}/${userStore().userInfo.uu_id}`;     // 注意：这里的friendId是以参数传递的
    const url = `http://localhost:8080/camelia/accept-friend-request/${userStore().userInfo.uu_id}`;
    console.log(friend);
    try {
        const response = await axiosInstance.post(url, friend);
        if (response) {
            console.log(response)
        }
    } catch (error: any) {
        console.log(error)
        if (error && error.status === 500) {
            ElMessage.error(error.response.data)
        }
    }
}


// 获取用户好友列表的api
export const getUserFriendList = async (): Promise<any> => {
    const user_store = userStore();
    const url = `http://localhost:8080/camelia/get-user-friend-info-list?userId=${user_store.userInfo.uu_id}`;
    try {
        const response = await axiosInstance.post(url);
        if (response) {
            return response.data;
        }
    } catch (error: any) {
        if (error && error.status === 401) {
            ElMessage.error(error.response.data.data);
        }
    }
}

// 拒绝好友请求的api
export const refuseFriendRequest = async (friendId: string): Promise<void> => {
    const user_store = userStore();
    const url = `http://localhost:8080/camelia/refuse-friend-request-info?fromUserId=${user_store.userInfo.uu_id}&toUserId=${friendId}`;
    try {
        const response = await axiosInstance.delete(url);
        if (response) {
            console.log(response);
        }
    } catch (error: any) {
        console.log(error.response.status)
        if (error && error.status === 500) {
            ElMessage.error(error.response.data.message);
        }
    }
}

// 测试接口（正在用！！！！！！！！！！！！！！！！！！！！！）
export const test = async (): Promise<void> => {
    const url = `http://localhost:8080/camelia/update-type-of-friendship/465180dc-53c2-4`;
    const testList = ['test1', 'play', 'sing']
    axiosInstance.post(url, testList).then((data): void => {
        console.log(data)
    }).catch((error): void => {
        console.error(error)
    })
}


// 创建群聊
export const createGroup = async (leaderId: string, groupInfo: any): Promise<void> => {
    console.log(groupInfo)
    const result = await callFactory();
    try {
        // 同时构建路径参数和矩阵变量参数
        let url = `http://localhost:8080/group/create-group/${leaderId}?pullGroupInfo=${encodeURIComponent(JSON.stringify(groupInfo))}`;
        try {
            const response = await axiosInstance.post(url, {}, {
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            if (response && response.data.status === 'OK') {
                // 保存对象信息状态，防御模式，避免后期的重置操作中会将已经保存的信息也进行重置（真的遇到过。。。。）
                // 在这里如果进行对象信息重置的话需要一个守护，多一个对象操作过程；如果不进行重置就少一个守护过程和清除对象信息过程
                const savedObjectState = { ...groupInfo };
                result.chat_store!.storageGroupInfo(savedObjectState);
                ElMessage.success(response.data.message);
            } else {
                ElMessage.warning(response.data.message);
            }
            // 重置对象信息
            pullGroupChats('clear');        // 很这个过程
        } catch (error) {
            console.error(error)
        }
    } catch (error) {
        console.error(error);
    }
}


// 获取当前用户群聊信息
// export const getBelongsGroup = async (): Promise<void> => {
//     // 等待pinia store的加载完成    在这里如果不等待pinia初始化的话就要延迟调用
//     const result = await callFactory();
//     if (factoryStatus.value) {
//         const uuId = result.user_store?.userInfo.uu_id;
//         try {
//             let url = `http://localhost:8080/group/get-user-belongs-chat-groups/${uuId}`;
//             const response = await axiosInstance.get(url);
//             if (response.data && Array.isArray(response.data)) {
//                 // 提取response.data中的数组数据
//                 const groupInfoArray = response.data as PullGroupBasicInfo[];
//                 result.chat_store?.storageGroupInfo(groupInfoArray);
//             }
//         } catch (error) {
//             console.error(error)
//         }
//     }
// }



// 删除好友
export const deleteFriend = async (friendId: string): Promise<void> => {
    const result = await callFactory();
    const userId = result.user_store?.userInfo.uu_id;
    let url = `http://localhost:8080/friend/delete-friend/${userId}/${friendId}`;
    ElMessage.warning(friendId)
    try {
        const response = await axiosInstance.post(url);
        if (response) {
            console.log(response)
            // 将response.status转换为一个数字，方便后期处理，也避免了ts的类型检查错误
            let status = Number(response.status);
            const message = response.data.message || "一不小心删除了一个好友"
            if (status === 200) {
                ElMessage.success(message);
            }
        }
    } catch (error: any) {
        console.log(error)
        const message = error.response.message || "删除好友失败";
        ElMessage.error(message)
    }
}


// 获取私聊信息
export const getFriendChatMessage = async (from: string, to: string): Promise<void> => {
    let url = `http://localhost:8080/chat/get-chat-message/${from}/${to}`;
    const result = await useFactory();
    try {
        const response = await axiosInstance.get(url);
        const data = response.data as StockPrivateMessage[];
        result.chat_store?.storeFriendMessage(to, data);
    } catch (error: any) {
        console.error(error);
    }
}
// 获取群聊信息
export const getGroupChatMessage = async (groupId: string): Promise<void> => {
    let url = `http://localhost:8080/chat/get-group-message/${groupId}`;
    const result = await useFactory();
    try {
        const response = await axiosInstance.get(url);
        const data = response.data as StockGroupMessage[];
        result.chat_store?.storeGroupMessage(groupId, data);
    } catch (error) {
        console.error(error);
    }
}


// 获取离线私聊信息
export const getOffLineMessageInfo = async (receiverId: string, senderId: string): Promise<any> => {
    let url = `http://localhost:8080/chat/get-off-online-friend-message/${receiverId}/${senderId}`;
    try {
        const response = await axiosInstance.get(url);
        if (response) {
            return response;
        }
    } catch (error: any) {
        console.error(error.response.status);
    }
}
// 获取离线群聊信息
export const getOffLineGroupMessage = async (userId: string, groupId: string): Promise<any> => {
    let url = `http://localhost:8080/chat/get-off-online-group-message/${groupId}/${userId}`;
    try {
        const response = await axiosInstance.get(url);
        console.log(response);
        if (response) {
            return response;
        }
    } catch (error: any) {
        console.log(error.response.status);
    }
}


// 获取聊天列表
export const getChatList = async (): Promise<void> => {
    let url = `http://localhost:8080/friend/get-chat-friend-list/${userStore().userInfo.uu_id}`;
    try {
        const response = await axiosInstance.get(url);
        const data = response.data;
        friendStore().storageList(data['groupList'], data['friendList']);
    } catch (error) {
        console.error(error);
    }
}


// 随机获取音乐信息
export const randomMusic = async (): Promise<void> => {
    try {
        const response = await axiosInstance.get<Music[]>(`http://localhost:8080/music/random-music`);
        if (response) {
            // 在这里扩展对象属性
            const processedData = response.data.map((musicItem: Music) => {
                return {
                    ...musicItem,
                    showExtra: false
                }
            })
            musicStore().storageMusicInfoList(processedData);
        }
    } catch (error) {
        console.error(error);
    }
}


// 获取音频文件的访问链接，成功获取之后存储到
export async function getMusicUrl(music_key: string): Promise<string | undefined> {
    let url = `http://localhost:8080/music/get-music-url`;
    try {                   // 注意：这里的参数有固定格式，第一个是url地址，第二个是请求体内容，没有请求体就是空对象,第三个是查询参数，可以是params也可以是headers
        const response = await axiosInstance.post(url, {}, {
            params: {
                musicKey: music_key
            }
        })
        if (response && response.data.status === 'success') {
            return response.data.musicUrl;
        }
    } catch (error: any) {
        if (error) {
            console.log(error.response);
            return;
        }
    }
}


// 获取音乐的歌词文件内容
export const getMusicLyrics = async (key: string): Promise<string | undefined> => {
    let url = "http://localhost:8080/music/get-music-lyrics";
    try {
        const response = await axiosInstance.post(url, {}, {
            params: {
                musicKey: key
            }
        })
        if (response && response.data.status === 'success') {
            return response.data.lyricContent;
        }
    } catch (error) {
        console.error(error);
    }
}
// 获取用户喜欢的音乐列表
export async function getUserLikeList(): Promise<void> {
    let url = "http://localhost:8080/music/get-user-music-like-list";
    try {
        const response = await axiosInstance.get(url, {
            params: {
                userId: userStore().userInfo.uu_id
            }
        });
        if (response && response.data.status === 'success') {
            musicStore().setLikeMusic(response.data.musicList);
        } else {
            if (response.data.musicList.length <= 0) {
                ElMessage.warning("暂无喜欢列表");
            }
        }
    } catch (error) {
        console.error(error);
    }
}

// 添加喜欢的音乐
export const addLikeMusic = async (musicKey: string, musicName: string, singer: string): Promise<void> => {
    const requestData: Music = {
        music_key: musicKey,
        music_name: musicName,
        singer: singer
    }
    let url = "http://localhost:8080/music/add-like-music";
    try {
        const response = await axiosInstance.post(url, requestData, {
            params: {
                uuId: userStore().userInfo.uu_id
            }
        })
        if (response && response.data.status === 'success') {
            ElMessage.success(response.data.message)
            musicStore().setLikeMusic(requestData)
        } else if (response.data.status === 'exists') {
            ElMessage.warning(response.data.message)
        } else {
            ElMessage.error(response.data.message);
        }
    } catch (error) {
        console.log(error);
    }
}

